package org.skipper.spring.cloud.dubbo.helper;

import lombok.extern.log4j.Log4j2;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import org.apache.dubbo.rpc.service.GenericService;
import org.skipper.common.RpcResult;
import org.skipper.common.constant.CommonCodeEnum;

import java.util.Arrays;

import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER;
import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author shoujian
 * Date: 2020-11-27
 * Time: 6:48 下午
 */
@Activate(group = {PROVIDER, CONSUMER})
@Log4j2
public class SpringCloudDubboRpcLog implements Filter {

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {

        long startTime = System.currentTimeMillis();

        Result result = invoker.invoke(invocation);

        long elapsed = System.currentTimeMillis() - startTime;

        if (result.hasException() && GenericService.class != invoker.getInterface()) {
            log.error("InterfaceName={},MethodName={},Params={},RpcError = {}",
                    invocation.getInvoker().getInterface().getName(), invocation.getMethodName(), invocation.getArguments(),
                    result.getException() + " " + Arrays.toString(result.getException().getStackTrace()));

            result.setValue(RpcResult.createErrorMsg(CommonCodeEnum.FAIL.getCode()));
            result.setException(null);//注意这里的exception要置为空，否则无效
        } else {
            log.info("InterfaceName={},MethodName={},Params={},Response={},SpendTime={} ms",
                    invocation.getInvoker().getInterface().getName(), invocation.getMethodName(), invocation.getArguments(),
                    result.getValue(), elapsed);
        }

        return result;
    }
}
